/*
=== 用户管理控制器 - 已废弃 ===

此文件已被注释，因为已迁移到动态API系统

替代方案：
- 动态API端点：/api/dynamic/users/*
- 管理端点：/api/DynamicApiManagement/endpoints
- 迁移指南：docs/API_MIGRATION_GUIDE.md

原始代码保留在注释中，如需回滚可以取消注释

using Microsoft.AspNetCore.Mvc;
using AuthService.Application.Services;
using AuthService.Domain.Entities;

namespace AuthService.Api.Controllers;

/// <summary>
/// 用户管理控制器
/// 提供用户的CRUD操作和权限管理
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly ILogger<UserController> _logger;
    private readonly IUserService _userService;

    public UserController(ILogger<UserController> logger, IUserService userService)
    {
        _logger = logger;
        _userService = userService;
    }

    /// <summary>
    /// 获取用户列表
    /// </summary>
    /// <param name="page">页码，从1开始，默认为1</param>
    /// <param name="size">每页大小，范围1-100，默认为10</param>
    /// <returns>返回分页的用户列表，包含用户基本信息和分页元数据</returns>
    /// <response code="200">成功获取用户列表</response>
    /// <response code="400">请求参数错误（如页码小于1或每页大小超出范围）</response>
    /// <response code="500">服务器内部错误</response>
    /// <example>
    /// GET /api/user?page=1&amp;size=10
    /// </example>
    [HttpGet]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(400)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetUsers(
        [FromQuery] int page = 1,
        [FromQuery] int size = 10,
        [FromQuery] string? search = null)
    {
        try
        {
            _logger.LogInformation("获取用户列表，页码: {Page}, 大小: {Size}, 搜索: {Search}", page, size, search);

            // 根据是否有搜索关键词选择不同的服务方法
            var (users, totalCount) = string.IsNullOrWhiteSpace(search)
                ? await _userService.GetUsersAsync(page, size)
                : await _userService.SearchUsersAsync(search, page, size);

            var result = new
            {
                Data = users.Select(u => new
                {
                    u.Id,
                    u.Username,
                    u.Email,
                    u.DisplayName,
                    u.IsActive,
                    u.IsEmailVerified,
                    u.IsLocked,
                    u.LastLoginAt,
                    u.CreatedAt,
                    u.UpdatedAt
                }),
                Total = totalCount,
                Page = page,
                Size = size,
                TotalPages = (int)Math.Ceiling(totalCount / (double)size)
            };

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户列表失败");
            return StatusCode(500, new { Message = "获取用户列表失败", Error = ex.Message });
        }
    }

    /// <summary>
    /// 根据ID获取用户详细信息
    /// </summary>
    /// <param name="id">用户ID，必须为正整数</param>
    /// <returns>返回用户的详细信息，包含基本资料、角色权限等</returns>
    /// <response code="200">成功获取用户信息</response>
    /// <response code="400">用户ID格式错误</response>
    /// <response code="404">用户不存在</response>
    /// <response code="500">服务器内部错误</response>
    /// <example>
    /// GET /api/user/123
    /// </example>
    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(400)]
    [ProducesResponseType(404)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetUser([FromRoute] Guid id)
    {
        try
        {
            _logger.LogInformation("获取用户详情，ID: {UserId}", id);

            var user = await _userService.GetUserByIdAsync(id);
            if (user == null)
            {
                return NotFound(new { Message = "用户不存在" });
            }

            var result = new
            {
                user.Id,
                user.Username,
                user.Email,
                user.DisplayName,
                user.IsActive,
                user.IsEmailVerified,
                user.CreatedAt,
                user.UpdatedAt,
                Roles = user.Roles,
                user.LastLoginAt
            };

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户详情失败，ID: {UserId}", id);
            return StatusCode(500, new { Message = "获取用户详情失败", Error = ex.Message });
        }
    }

    /// <summary>
    /// 创建新用户账户
    /// </summary>
    /// <param name="request">用户创建请求对象，包含用户名、邮箱等必要信息</param>
    /// <returns>返回创建成功的用户信息</returns>
    /// <response code="201">用户创建成功</response>
    /// <response code="400">请求参数错误（如用户名或邮箱格式不正确）</response>
    /// <response code="409">用户名或邮箱已存在</response>
    /// <response code="500">服务器内部错误</response>
    /// <example>
    /// POST /api/user
    /// {
    ///   "username": "newuser",
    ///   "email": "newuser@example.com",
    ///   "displayName": "新用户"
    /// }
    /// </example>
    [HttpPost]
    [ProducesResponseType(typeof(object), 201)]
    [ProducesResponseType(400)]
    [ProducesResponseType(409)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> CreateUser([FromBody] CreateUserRequest request)
    {
        try
        {
            _logger.LogInformation("创建用户，用户名: {Username}", request.Username);

            if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Email))
            {
                return BadRequest(new { Message = "用户名和邮箱不能为空" });
            }

            // 检查用户名是否已存在
            var existingUserByUsername = await _userRepository.GetByUsernameAsync(request.Username);
            if (existingUserByUsername != null)
            {
                return Conflict(new { Message = "用户名已存在" });
            }

            // 检查邮箱是否已存在
            var existingUserByEmail = await _userRepository.GetByEmailAsync(request.Email);
            if (existingUserByEmail != null)
            {
                return Conflict(new { Message = "邮箱已存在" });
            }

            // 创建新用户
            var user = new User
            {
                Username = request.Username,
                Email = request.Email,
                DisplayName = request.DisplayName ?? request.Username,
                PasswordHash = "temp_hash", // 临时密码哈希，实际应用中需要密码哈希服务
                PasswordSalt = "temp_salt", // 临时盐值
                IsActive = true,
                IsEmailVerified = false,
                Roles = new List<string> { "User" },
                CreatedBy = "system"
            };

            var createdUser = await _userRepository.CreateAsync(user);

            var result = new
            {
                createdUser.Id,
                createdUser.Username,
                createdUser.Email,
                createdUser.DisplayName,
                createdUser.IsActive,
                createdUser.CreatedAt
            };

            return CreatedAtAction(nameof(GetUser), new { id = createdUser.Id }, result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建用户失败，用户名: {Username}", request.Username);
            return StatusCode(500, new { Message = "创建用户失败", Error = ex.Message });
        }
    }

    /// <summary>
    /// 更新用户信息
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="request">更新请求</param>
    /// <returns>更新结果</returns>
    [HttpPut("{id:int}")]

    public async Task<IActionResult> UpdateUser(
        [FromRoute] int id,
        [FromBody] UpdateUserRequest request)
    {
        _logger.LogInformation("更新用户，ID: {UserId}", id);

        var user = new
        {
            Id = id,
            Username = request.Username,
            Email = request.Email,
            DisplayName = request.DisplayName,
            UpdatedAt = DateTime.Now
        };

        return Ok(user);
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{id:int}")]

    public async Task<IActionResult> DeleteUser([FromRoute] int id)
    {
        _logger.LogInformation("删除用户，ID: {UserId}", id);
        return NoContent();
    }
}

/// <summary>
/// 创建用户请求模型
/// </summary>
public class CreateUserRequest
{
    /// <summary>
    /// 用户名，长度3-50个字符，只能包含字母、数字和下划线
    /// </summary>
    /// <example>newuser</example>
    public string Username { get; set; } = string.Empty;

    /// <summary>
    /// 邮箱地址，必须符合邮箱格式
    /// </summary>
    /// <example>newuser@example.com</example>
    public string Email { get; set; } = string.Empty;

    /// <summary>
    /// 显示名称，可选，用于界面显示
    /// </summary>
    /// <example>新用户</example>
    public string? DisplayName { get; set; }
}

/// <summary>
/// 更新用户请求模型
/// </summary>
public class UpdateUserRequest
{
    /// <summary>
    /// 用户名，长度3-50个字符，只能包含字母、数字和下划线
    /// </summary>
    /// <example>updateduser</example>
    public string Username { get; set; } = string.Empty;

    /// <summary>
    /// 邮箱地址，必须符合邮箱格式
    /// </summary>
    /// <example>updateduser@example.com</example>
    public string Email { get; set; } = string.Empty;

    /// <summary>
    /// 显示名称，可选，用于界面显示
    /// </summary>
    /// <example>更新后的用户</example>
    public string? DisplayName { get; set; }
}

*/
